package com.iot.manager.network.interceptors;

import android.util.Log;

import com.google.gson.Gson;
import com.iot.manager.network.ApiError;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class ErrorInterceptor implements Interceptor {
    private static final String TAG = "ErrorInterceptor";
    private final Gson gson = new Gson();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        if (!response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                try {
                    ApiError error = gson.fromJson(responseString, ApiError.class);
                    Log.e(TAG, "API Error: " + error.getMessage() + " (Status: " + error.getStatus() + ")");
                    // 这里可以添加全局错误处理逻辑
                } catch (Exception e) {
                    Log.e(TAG, "Error parsing error response: " + e.getMessage());
                }
                // 重新创建 ResponseBody，因为原来的已经被消费了
                response = response.newBuilder()
                        .body(ResponseBody.create(responseBody.contentType(), responseString))
                        .build();
            }
        }

        return response;
    }
} 